## 

rm(list = ls())

##

library(tidyverse)
library(lubridate)

## Get data 

civ <- read_rds("data/civey_party_replication.rds")

## Monthly intervals

start <- as.Date("2021-01-01")
end <- as.Date("2021-10-01")

dates_m <- floor_date(seq(start, end, by = 'month'), 
                      unit = "month") + 11

## Month indicators

civ <- civ %>% 
  mutate(month_10 = cut(date, dates_m)) %>% 
  mutate(month_10 = as.numeric(as.factor(month_10)) - 7) %>% 
  filter(!is.na(month_10))

## Balance variables

bvars <- c('educ', 'age', 'gender')

## Dummy cols

civ <- civ %>% 
  fastDummies::dummy_cols(bvars) %>% 
  dplyr::select(month_10, 
                matches("age|educ|gender"), 
                matches("treat")) %>% 
  dplyr::select(-age, -educ, -gender)

## Aggregate all 

civ <- civ %>% 
  pivot_longer(-c(month_10, treat_categ)) %>% 
  group_by(month_10, name, treat_categ) %>% 
  summarise(m = mean(value, na.rm = T),
            m_se = sd(value, na.rm = T) / sqrt(n())) %>% 
  ungroup() %>% 
  mutate(what = str_extract(name, '^[^_]+(?=_)')) %>% 
  mutate(treat_label = recode(treat_categ,
                              'none' = 'Unaffected',
                              'schwach' = 'Weakly affected',
                              'schwer' = 'Highly affected')) %>% 
  mutate(treat_label = fct_relevel(treat_label,
                                   'Highly affected', 'Weakly affected'))


## Create dictionary

dict_df <- c("age_18-29-Jährige", "age_30-39-Jährige", "age_40-49-Jährige", 
             "age_50-64-Jährige", "age_NA", "age_Über 65-Jährige", "educ_Abitur / Noch in schulischer Ausbildung", 
             "educ_Hauptschule / Kein Abschluss", "educ_Mittlere Reife", "educ_NA", 
             "gender_Frauen", "gender_Männer") %>% 
  data.frame(name = ., name_new = c("18-29", "30-39", "40-49", 
                                    "50-64", "Missing", "65+", 
                                    "Abitur / in educ.",
                                    "Hauptschule", "Mittlere Reife", 
                                    "Missing", "Female", "Male"))

## Merge dictionary

civ <- civ %>% 
  left_join(dict_df)

## Plot function

make_plot <- function(what_val = 'educ') {
  
  civ %>% 
    filter(what == what_val) %>% 
    ggplot(aes(month_10, m * 100)) +
    geom_line(aes(color = treat_label)) +
    ylab("Share of respondents (%)") + 
    xlab("Months rel. to flood") +
    scale_x_continuous(breaks = -10:10) + 
    theme_bw() +
    scale_color_grey(name = 'Flood intensity') +
    scale_fill_grey(name = 'Flood intensity') +
    theme(legend.position = "bottom") +
    facet_wrap(~name_new)
  
  
}

#### Figure A.5 - education ####

make_plot("educ")

#### Figure A.6 - gender ####

make_plot("gender")

#### Figure A.7 - age ####

make_plot("age") +
  facet_wrap(~name_new, ncol = 2)
